import { queryDrawYear } from "@/api/drawHist";
import useSelYr, { useSelYrRefs } from "./useSelYr";
import useFetchStats, { useFetchStatsRefs } from "../../hooks/useFetchStats";

const useFetchYr = defineStore("lotStats-fetchYr", () => {
  const yearList = ref<(string | number)[]>([]);
  const { initYear } = useSelYr();
  const { yearRange } = useSelYrRefs();
  const { updateParams } = useFetchStats();
  const { params } = useFetchStatsRefs();

  async function fetchDrawYr() {
    const res = await queryDrawYear();
    yearList.value = res?.data ?? [];
    const end_year = Number(yearList.value[0]);
    const start_year = Number(yearList.value[yearList.value.length - 1]);
    if (unref(yearRange).length) {
      updateParams({
        ...params.value,
        start_year: unref(yearRange)[0],
        end_year: unref(yearRange)[1]
      });
      return;
    }
    initYear([start_year, end_year]);
    updateParams({
      ...params.value,
      start_year: start_year,
      end_year: end_year
    });
  }
  onMounted(() => {
    console.log("useFetchYr");
    fetchDrawYr();
  });
  return { yearList, fetchDrawYr };
});
export const useFetchYrRefs = () => storeToRefs(useFetchYr());
export default useFetchYr;
